import tkinter as tk

def computer():
    #初始化列表
    listbox1.delete(1,tk.END)
    #获取A城的温度列表和截止时间列表
    data1 = txt1.get().split(";")
    temperature1 = []
    time1 = []
    for item in data1:
        tmp = item.split(",")
        temperature1.append(int(tmp[0]))
        time1.append(int(tmp[1]))
    # 获取B城的温度列表和截止时间列表
    data2 = txt2.get().split(";")
    temperature2 = []
    time2 = []
    for item in data2:
        tmp = item.split(",")
        temperature2.append(int(tmp[0]))
        time2.append(int(tmp[1]))
    #将A城第i个记录中的截止时间转换为持续时长
    real = time1[:1]
    for i in range(1, len(time1)):
        real.append(time1[i] - time1[i-1])

    #持续时长最大为1小时，拆分温度数据
    result1 = []
    result2 = []
    for i in range(len(real)):
        for j in range(real[i]):
            result1.append(temperature1[i])
    for i in range(len(time2)):
        for j in range(time2[i]):
            result2.append(temperature2[i])
    #计算每个时段的温度差，得到列表
    diff = []
    for i in range(len(result1)):
        diff.append(result1[i]-result2[i])
    #计获取计算结果
    put = []
    count = 1
    item = diff[0]
    for i in range(1, len(diff)):
        if(diff[i] == diff[i-1]):
            count = count + 1
        else:
            put.append(str(item) + "," + str(count))
            count = 1
            item = diff[i]
        if (i == len(diff) - 1):
            put.append(str(item) + "," + str(count))
    #输出到表格
    for i in range(len(put)):
        listbox1.insert(tk.END, '  ' + put[i].split(",")[0] + '       ' + put[i].split(",")[1])


# 建立窗口
win = tk.Tk()
win.title('两城温差')
win.resizable(0, 0)
# 建立组件
lb1 = tk.Label(win, text = '输入A城温度数据(数据格式：温度,截止时间;)：')
lb2 = tk.Label(win, text = '输入B城温度数据(数据格式：温度,持续时长;)：')
listbox1 = tk.Listbox(win)
listbox1.insert(0, '  温差    持续时长')
txt1 = tk.Entry(win)
txt1.insert(0, '30,2;33,4;31,6;32,7')
txt2 = tk.Entry(win)
txt2.insert(0, '20,3;22,1;21,2;22,1')
cmd = tk.Button(win, text = '计算温差', command = computer)

# 组件布局
lb1.grid(row = 0, column = 0)
lb2.grid(row = 1, column = 0)
txt1.grid(row = 0, column = 1, padx = 10, ipadx = 10)
txt2.grid(row = 1, column = 1, padx = 10, ipadx = 10)
cmd.grid(row = 2, column = 0)
listbox1.grid(row = 0, column = 2 ,rowspan = 3)
# 接收窗口事件
win.mainloop()
